import os

from pydub import AudioSegment

from utils.file_io import file_r, file_w

transcript_short_path = "transcript/transcript_short.txt"
sound_root_path = "wav"
transcript_root_path = "transcript"
min_text = 5  # 当拼接出的文本长度长于此值时才会输出一段
min_second = 0.1  # 当拼接出的音频长度长于此值时才会输出一段
transcript_short_text = file_r("transcript/transcript_short.txt")
file_name = ""
file_name_begin = ""
file_list = []
file_text = ""

def get_sound_time(file_list):
    sound_all_this = AudioSegment.silent(1)
    for wav_file_this in file_list:
        sound_all_this = sound_all_this + AudioSegment.from_wav(
            sound_root_path + "/output_short/" + file_name_begin + "_" + wav_file_this + ".wav")
    sound_time = sound_all_this.duration_seconds
    return sound_time

def main():
    """
    合并过短的音频
    """
    global file_name_begin
    if not os.path.exists(sound_root_path+"/output/"):
        os.mkdir(sound_root_path+"/output/")
    for line in transcript_short_text.split("\n"):
        if len(line) == 0:
            continue
        line_file_name = line.split(" ")[0]
        file_name_list = line_file_name.split("_")
        file_name_list.remove(file_name_list[-1])
        if file_name_begin != "_".join(file_name_list):
            file_text = ""
            file_list = []
        file_name_begin = "_".join(file_name_list)  # list.remove函数返回值为none
        file_text = file_text + line.split(" ")[1]
        file_list.append(line_file_name.split("_")[-1])
        print(get_sound_time(file_list))
        if len(file_text) > min_text and get_sound_time(file_list) > min_second:
            file_name = file_name_begin + "_" + "_".join(file_list)
            sound_all = AudioSegment.silent(1)
            for wav_file in file_list:
                sound_all = sound_all + AudioSegment.from_wav(sound_root_path + "/output_short/" + file_name_begin + "_" + wav_file + ".wav" )
            sound_all.export(sound_root_path + "/output/" + file_name + ".wav", format="wav")
            file_w(transcript_root_path + "/transcript.txt",file_name + " " + file_text + "\n", "a")
            file_text = ""
            file_list = []

if __name__ == "__main__":
    main()
